package com.yonyou.le.unattended.websocket;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import com.google.gson.Gson;

/**
 * websockethandler消息处理Handler
 * @author zhangbbd
 */
public class MonitorWSS extends TextWebSocketHandler {
	private final Logger logger = LoggerFactory.getLogger(getClass());
	
	
	@Override
	public void afterConnectionEstablished(WebSocketSession session) throws Exception {
		logger.info("新建立连接sessionID="+session.getId());
	}
	
	/**
	 * 收到前台发来的实时作业点信息
	 */
	@Override
	public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
		logger.info("Received: " + message.getPayload().toString());			
		Gson gson =new Gson();
		MonitorMsg msg=gson.fromJson((String) message.getPayload(), MonitorMsg.class);
		if(MsgTypeEnum.WS_TYPE_OPADD.getName().equals(msg.getMsgType())){//增加作业点
			MonitorUtils.putSession(msg.getOpcode(), session);
		}else if(MsgTypeEnum.WS_TYPE_OPDELETE.getName().equals(msg.getMsgType())){//删除作业点
			MonitorUtils.removeByOpcode(msg.getOpcode());
		}else if(MsgTypeEnum.WS_TYPE_HEARTCHECK.getName().equals(msg.getMsgType())){//心跳包，测试连接是否正常
			MonitorUtils.sendMessage(MsgTypeEnum.WS_TYPE_HEARTCHECK.getName(), "", "");
		}	
	}

	@Override
	public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
		if (session.isOpen()) {
			session.close();
		}
		MonitorUtils.removeBySession(session.getId());
	}

	@Override
	public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
		MonitorUtils.removeBySession(session.getId());
	}

	@Override
	public boolean supportsPartialMessages() {
		return false;
	}
	

}
